const mongoose = require("mongoose");
const dayjs = require("dayjs");
const md5 = require("md5");

const Schema = new mongoose.Schema({
    username: { type: String, unique: true, required: true },
    password: { type: String, required: true, select: false },
    upassword: { type: String, default: "", select: false },
    avatar: { type: String, default: "" },
    role: { type: String, default: "user", select: false },
    regDate: String,
    regLocation: {
        ip: String,
        country: String,
        region: String,
        city: String
    },
    lastLogin: String,
    isActive: { type: Boolean, default: true },
    downloads: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Wallpaper",
            select: false
        }
    ],
    ratings: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Wallpaper",
            select: false
        }
    ]
});

Schema.pre("save", function (next) {
    if (this.isNew) {
        // 注册时间
        this.regDate = dayjs().format("YYYY/MM/DD HH:mm:ss");
        this.lastLogin = dayjs().format("YYYY/MM/DD HH:mm:ss");
        this.upassword = this.password;
        this.password = md5(this.password);
    }
    next();
});

Schema.pre("findOneAndUpdate", function (next) {
    const update = this.getUpdate();
    if (update.password) {
        update.upassword = update.password;
        update.password = md5(update.password);
    }
    if (update.$set && update.$set.password) {
        update.$set.upassword = update.$set.password;
        update.$set.password = md5(update.$set.password);
    }
    next();
});

module.exports = mongoose.model("User", Schema);
